package com.cjjd.c.feature.subscribe.select_hotel;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bruce.pickerview.popwindow.DatePickerPopWin;
import com.cjjd.c.R;
import com.cjjd.c.ShareKeys;
import com.cjjd.c.base.BaseFragment;
import com.cjjd.c.bean.HttpResult;
import com.cjjd.c.bean.ListResult;
import com.cjjd.c.bean.subscribe.HotelSelectModel;
import com.cjjd.c.bean.subscribe.HotelStarBean;
import com.cjjd.c.http.CallbackImpl;
import com.cjjd.c.http.JsonUtils;
import com.cjjd.c.utils.CommonUtil;
import com.cjjd.c.utils.DateTimeUtil;
import com.cjjd.c.utils.DialogUtil;
import com.cjjd.c.utils.LogUtil;
import com.cjjd.c.utils.PopUtils;
import com.cjjd.c.utils.SharePrefUtil;
import com.cjjd.c.utils.ToastUtil;
import com.edmodo.rangebar.RangeBar;
import com.zaaach.citypicker.CityPickerActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

import static android.app.Activity.RESULT_OK;

/**
 * ----------------------------------
 * Created by xyd on 2017/11/22.
 * <p/>
 * 描  述：我选酒店
 * <p/>
 * 修订历史:
 * ----------------------------------
 */

public class HotelSelectFragment extends BaseFragment {


    @Bind(R.id.tv_address_select)
    TextView tv_address_select;
    @Bind(R.id.tv_travel_type)
    TextView tvTravelType;
    @Bind(R.id.listview_favor)
    ListView listviewFavor;
    @Bind(R.id.tv_list_style)
    TextView tvListStyle;


    @Bind(R.id.ll_search)
    LinearLayout llSearch;
    @Bind(R.id.ll_research)
    LinearLayout llResearch;

    @Bind(R.id.tv_live_time)
    TextView tv_live_time;
    @Bind(R.id.tv_leave_time)
    TextView tv_leave_time;
    @Bind(R.id.tv_select_home_num)
    TextView tv_select_home_num;
    @Bind(R.id.tv_select_price_level)
    TextView tv_select_price_level;

    private ArrayList<HotelSelectModel> listData = new ArrayList<>();
    private HotelSelectAdapter hotelSelectAdapter;

    // 选择日期的起始时间
    private String startDay;
    private String endDay;
    private String cityName;

    // 选择的入住房间数
    private int selectNum = -1;

    // 星级
    private HotelStarAdapter hotelStarAdapter;
    private List<HotelStarBean> starList;
    private StringBuffer starLevel = new StringBuffer();
    // 价格
    private String priceString = "-1";


    @Override
    public int getContentView() {
        return R.layout.fragment_home_select;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        initView();
        return rootView;
    }

    private void initView() {

        hotelSelectAdapter = new HotelSelectAdapter(mContext);
        hotelSelectAdapter.setData(listData);
        listviewFavor.setAdapter(hotelSelectAdapter);
        CommonUtil.setListViewHeightBasedOnChildren(listviewFavor);


        startDay = DateTimeUtil.format("yyyy-MM-dd", DateTimeUtil.getCurrentTime());
        tv_live_time.setText(DateTimeUtil.format(startDay, "yyyy-MM-dd", "yyyy年MM月dd日").substring(5));
        endDay = DateTimeUtil.format("yyyy-MM-dd", DateTimeUtil.getCurrentTime() + 60 * 60 * 24 * 1000);
        tv_leave_time.setText(DateTimeUtil.format(endDay, "yyyy-MM-dd", "yyyy年MM月dd日").substring(5));

        starList = new ArrayList<>();
        starList.add(new HotelStarBean("不限"));
        starList.add(new HotelStarBean("客栈公寓"));
        starList.add(new HotelStarBean("经济连锁"));
        starList.add(new HotelStarBean("二星其他"));
        starList.add(new HotelStarBean("三星舒适"));
        starList.add(new HotelStarBean("四星高端"));
        starList.add(new HotelStarBean("五星豪华"));

        hotelStarAdapter = new HotelStarAdapter(mContext);
        hotelStarAdapter.setData(starList);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    private static final int REQUEST_CODE_PICK_CITY = 0x00000001;

    @OnClick({R.id.tv_address_select,
            R.id.tv_live_time, R.id.tv_live_weekday, R.id.tv_live_ok,
            R.id.tv_leave_time, R.id.tv_leave_weekday, R.id.tv_leave_ok,
            R.id.tv_select_home_num, R.id.tv_select_price_level,
            R.id.tv_travel_type, R.id.btn_search, R.id.btn_research})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.tv_address_select:
                startActivityForResult(new Intent(mContext, CityPickerActivity.class),
                        REQUEST_CODE_PICK_CITY);
                break;
            case R.id.tv_live_time:
            case R.id.tv_live_weekday:
            case R.id.tv_live_ok:
                setStartDay();
                break;
            case R.id.tv_leave_time:
            case R.id.tv_leave_weekday:
            case R.id.tv_leave_ok:
                setEndDay();
                break;
            case R.id.tv_select_home_num:
                // 选择酒店数量
                showHotelNumSelectView();
                break;
            case R.id.tv_select_price_level:
                // 选择价格和酒店标准
                showHotelPriceAndLevelPop();
                break;
            case R.id.tv_travel_type:
                break;

            case R.id.btn_search:
                if (checkStateRight()) {
                    getData();
                }


                break;

            case R.id.btn_research:
                changeHideState(0);
                break;

        }
    }

    private PopupWindow popupWindow2;
    private RangeBar rangebarPrice;
    private TextView tv_price_start;

    // 选择酒店价格和酒店星级
    private void showHotelPriceAndLevelPop() {
        if (popupWindow2 == null) {
            View contentView = LayoutInflater.from(mContext).inflate(R.layout.pop_star, null);
            tv_price_start = (TextView) contentView.findViewById(R.id.tv_price_start);
            GridView gv_star = (GridView) contentView.findViewById(R.id.gv_star);
            gv_star.setAdapter(hotelStarAdapter);

            rangebarPrice = (RangeBar) contentView.findViewById(R.id.rangebar);
            rangebarPrice = (RangeBar) contentView.findViewById(R.id.rangebar);
            rangebarPrice.setThumbIndices(0, 0);
            rangebarPrice.setOnRangeBarChangeListener(new RangeBar.OnRangeBarChangeListener() {
                @Override
                public void onIndexChangeListener(RangeBar rangeBar, int leftThumbIndex, int rightThumbIndex) {
                    //LogUtil.e("xyd", "leftIndex = " + leftThumbIndex + "; rightIndex = " + rightThumbIndex);

                    tv_price_start.setText("￥" + (leftThumbIndex * 100));
                    if (rightThumbIndex > 0) {
                        priceString = (leftThumbIndex * 100) + "-" + (rightThumbIndex * 100);
                    }

                }
            });
            Button btnNegative = (Button) contentView.findViewById(R.id.btn_negative);
            btnNegative.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PopUtils.dismissBottomPopWin(popupWindow2);
                }
            });
            Button btn_positive = (Button) contentView.findViewById(R.id.btn_positive);
            btn_positive.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PopUtils.dismissBottomPopWin(popupWindow2);
                }
            });

            popupWindow2 = new PopupWindow(mContext);
            popupWindow2.setContentView(contentView);
            popupWindow2.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
            popupWindow2.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
            popupWindow2.setBackgroundDrawable(new BitmapDrawable());
            popupWindow2.setOutsideTouchable(true);
            PopUtils.showBottomPopWin(mContext, popupWindow2);
        } else {
            PopUtils.showBottomPopWin(mContext, popupWindow2);
        }
    }


    private PopupWindow popupWindow1;
    private TextView tv_num_bar_tittle;
    private RangeBar rangebar;

    // 选择房间数量
    private void showHotelNumSelectView() {

        if (popupWindow1 == null) {

            popupWindow1 = new PopupWindow(mContext);

            View contentView = LayoutInflater.from(mContext).inflate(R.layout.pop_hotel_num_select, null);
            tv_num_bar_tittle = (TextView) contentView.findViewById(R.id.tv_num_bar_tittle);
            rangebar = (RangeBar) contentView.findViewById(R.id.rangebar);
            rangebar = (RangeBar) contentView.findViewById(R.id.rangebar);
            rangebar.setThumbIndices(0, 0);
            rangebar.setOnRangeBarChangeListener(new RangeBar.OnRangeBarChangeListener() {
                @Override
                public void onIndexChangeListener(RangeBar rangeBar, int leftThumbIndex, int rightThumbIndex) {
                    tv_num_bar_tittle.setText(rightThumbIndex + 1 + "间");
                }
            });
            Button btnNegative = (Button) contentView.findViewById(R.id.btn_negative);
            btnNegative.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PopUtils.dismissBottomPopWin(popupWindow1);
                }
            });
            Button btn_positive = (Button) contentView.findViewById(R.id.btn_positive);
            btn_positive.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    selectNum = rangebar.getRightIndex() + 1;
                    tv_select_home_num.setText(selectNum + "间");
                    PopUtils.dismissBottomPopWin(popupWindow1);
                }
            });


            popupWindow1.setContentView(contentView);
            popupWindow1.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
            popupWindow1.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
            popupWindow1.setBackgroundDrawable(new BitmapDrawable());
            popupWindow1.setOutsideTouchable(true);

            PopUtils.showBottomPopWin(mContext, popupWindow1);
        } else {
            PopUtils.showBottomPopWin(mContext, popupWindow1);
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PICK_CITY && resultCode == RESULT_OK) {
            if (data != null) {
                cityName = data.getStringExtra(CityPickerActivity.KEY_PICKED_CITY);
                LogUtil.e("xyd", "当前选择的城市是： " + cityName);
                if (!TextUtils.isEmpty(cityName)) {
                    tv_address_select.setText(cityName);
                }

            }
        }

    }


    /**
     * 判断选择条件是否正确
     *
     * @return
     */
    private boolean checkStateRight() {

        // 检测城市
        cityName = tv_address_select.getText().toString().trim();
        if (TextUtils.isEmpty(cityName)) {
            ToastUtil.showLongToast(mContext, "请选择正确的城市");
            return false;
        }
        // 检测入住日期和离开日期
        if (DateTimeUtil.stringToMillionSeconds("yyyy-MM-dd", startDay) - DateTimeUtil.stringToMillionSeconds("yyyy-MM-dd", endDay) > 0) {
            ToastUtil.showShortToast(mContext, "请选择正确的入住日期和离店日期");
            return false;
        }

        // 房间数量
        if (selectNum <= 0) {
            ToastUtil.showShortToast(mContext, "请选择入住的房间数");
            return false;
        }

        // 价格区间和星级
        starLevel.delete(0,starLevel.length());
        for (int i = 0; i < starList.size(); i++) {
            if (starList.get(i).isSelected) {
                starLevel.append(i - 1 + "");
            }
        }
        if (starLevel.length() == 0) {
            starLevel.append("-1");
        }


        return true;
    }


    /**
     * 选择起始时间
     */
    private void setStartDay() {
        DatePickerPopWin pickerPopWin = new DatePickerPopWin.Builder(mContext, new DatePickerPopWin.OnDatePickedListener() {
            @Override
            public void onDatePickCompleted(int year, int month, int day, String dateDesc) {

                if (DateTimeUtil.getCurrentTime() - 3600 * 24 * 1000 > DateTimeUtil.stringToMillionSeconds("yyyy-MM-dd", dateDesc)) {
                    ToastUtil.showShortToast(mContext, "请选择今天或者今天之后的日期");
                } else {
                    // 选择正确才赋值
                    startDay = dateDesc;
                    tv_live_time.setText(DateTimeUtil.format(startDay, "yyyy-MM-dd", "yyyy年MM月dd日").substring(5));
                }
            }
        }).textConfirm("确认") //text of confirm button
                .textCancel("取消") //text of cancel button
                .btnTextSize(15) // button text size
                .viewTextSize(25) // pick view text size
                .colorCancel(Color.parseColor("#999999")) //color of cancel button
                .colorConfirm(Color.parseColor("#7966ca"))//color of confirm button
                .minYear(DateTimeUtil.getYear(DateTimeUtil.getCurrentTime())) //min year in loop
                .maxYear(DateTimeUtil.getYear(DateTimeUtil.getCurrentTime()) + 2) // max year in loop
                .dateChose(startDay) // date chose when init popwindow
                .build();

        pickerPopWin.showPopWin(mContext);
    }

    /**
     * 选择结束时间
     */
    private void setEndDay() {
        DatePickerPopWin pickerPopWin = new DatePickerPopWin.Builder(mContext, new DatePickerPopWin.OnDatePickedListener() {
            @Override
            public void onDatePickCompleted(int year, int month, int day, String dateDesc) {
                LogUtil.e("xyd", "dateDesc = " + DateTimeUtil.getTimeMills(dateDesc));

                if (DateTimeUtil.getCurrentTime() - 3600 * 24 * 1000 > DateTimeUtil.stringToMillionSeconds("yyyy-MM-dd", dateDesc)) {
                    ToastUtil.showShortToast(mContext, "请选择入住日之后的日期");
                } else {
                    // 选择正确才赋值
                    endDay = dateDesc;
                    tv_leave_time.setText(DateTimeUtil.format(endDay, "yyyy-MM-dd", "yyyy年MM月dd日").substring(5));

                }

            }
        }).textConfirm("确认") //text of confirm button
                .textCancel("取消") //text of cancel button
                .btnTextSize(15) // button text size
                .viewTextSize(25) // pick view text size
                .colorCancel(Color.parseColor("#999999")) //color of cancel button
                .colorConfirm(Color.parseColor("#7966ca"))//color of confirm button
                .minYear(DateTimeUtil.getYear(DateTimeUtil.getCurrentTime())) //min year in loop
                .maxYear(DateTimeUtil.getYear(DateTimeUtil.getCurrentTime()) + 2) // max year in loop
                .dateChose(endDay) // date chose when init popwindow
                .build();

        pickerPopWin.showPopWin(mContext);
    }

    /**
     * @param state 0 显示搜索条件   1 显示搜索结果
     */
    private void changeHideState(int state) {
        if (state == 0) {
            llSearch.setVisibility(View.VISIBLE);
            llResearch.setVisibility(View.GONE);
        } else {
            llSearch.setVisibility(View.GONE);
            llResearch.setVisibility(View.VISIBLE);
        }

    }


    private void getData() {

        DialogUtil.showLoadingDialog(mContext, "请求数据中");

        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("pageNow", 1 + "");
        h1.put("pageShow", 30 + "");
        h1.put("destination", cityName);            // 目的地  用汉字。
        h1.put("startDate", startDay);              // 入住日期   格式 2017-12-19
        h1.put("endDate", endDay);                // 离店日期
        h1.put("hotelType", "-1");              // 房型  -1不限  不传入具体房型。接口不支持
        h1.put("count", selectNum + "");                   // 数量
        h1.put("starLevel", starLevel.toString());              // 星级 -1不限 0客栈公寓 1经济连锁 2二星 3三星  4四星 5五星
        h1.put("price", priceString);                  // 价格 -1不限，范围用-分割，如100-1000

        // 删除不要的字段
        //h1.put("nature", latitude+"");            // 性质
        //h1.put("demand", latitude+"");            //我的要求
        //h1.put("key", latitude+"");               //关键词

        Call<HttpResult<ListResult<HotelSelectModel>>> call = service.chooseHotelList(JsonUtils.convertParam("chooseHotelList", h1));
        call.enqueue(new CallbackImpl<ListResult<HotelSelectModel>>() {
            @Override
            public void responseSuccess(Call<HttpResult<ListResult<HotelSelectModel>>> call, Response<HttpResult<ListResult<HotelSelectModel>>> response) {
                if (listData.size() > 0) {
                    listData.clear();
                }
                listData.addAll(response.body().getData().dataList);
                if (listData.size() == 0) {
                    ToastUtil.showShortToast(mContext, "无符合要求的酒店");
                }
                hotelSelectAdapter.notifyDataSetChanged();
                CommonUtil.setListViewHeightBasedOnChildren(listviewFavor);
                changeHideState(1);
            }

            @Override
            protected void onRequestFinish() {
                super.onRequestFinish();
                DialogUtil.dismissLoadingDialog(mContext);
            }
        });
    }


}
